﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace InDepth2Demo.Chapter15
{
    internal class MakeBreakfast
    {
        public static void Call()
        {
            Test();
            Console.ReadLine();
        }

        private static void Test()
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Console.WriteLine("线程： " + Thread.CurrentThread.ManagedThreadId);
            List<Task> tasks = new List<Task>() { PourOJ(), ToastBread(), FryBacon(), FryEggs(), PourCoffee() };
            Task.WhenAll(tasks).ContinueWith((t) =>
            {
                Console.WriteLine("早餐已经做完!");
                stopwatch.Stop();
                Console.WriteLine($"做早餐总计耗时：{stopwatch.ElapsedMilliseconds} {Thread.CurrentThread.ManagedThreadId}");
            });
        }

        //倒橙汁
        private static async Task PourOJ()
        {
            await Task.Delay(1000);
            Console.WriteLine("倒一杯橙汁 " + Thread.CurrentThread.ManagedThreadId);
        }

        //烤面包
        private static async Task ToastBread()
        {
            Console.WriteLine("开始烤面包");
            await Task.Delay(3000);
            Console.WriteLine("烤面包好了 " + Thread.CurrentThread.ManagedThreadId);

        }

        //煎培根
        private static async Task FryBacon()
        {
            Console.WriteLine("开始煎培根");
            await Task.Delay(6000);
            Console.WriteLine("培根煎好了 " + Thread.CurrentThread.ManagedThreadId);
        }
        //煎鸡蛋
        private static async Task FryEggs()
        {
            Console.WriteLine("开始煎鸡蛋");
            await Task.Delay(6000);
            Console.WriteLine("鸡蛋好了 " + Thread.CurrentThread.ManagedThreadId);
        }

        //倒咖啡
        private static async Task PourCoffee()
        {
            await Task.Delay(1000);
            Console.WriteLine("倒咖啡 " + Thread.CurrentThread.ManagedThreadId);
        }


        // 并行且可指定顺序执行
        // 如果现在要求，先倒橙汁，然后倒咖啡，其余的操作并行执行，应该如何操作呢？
        private static async void Test2()
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            await PourOJ();
            await PourCoffee();
            List<Task> tasks = new List<Task>() { ToastBread(), FryBacon(), FryEggs() };
            await Task.WhenAll(tasks);
            Console.WriteLine("早餐已经做完!");
            stopwatch.Stop();
            Console.WriteLine($"做早餐总计耗时：{stopwatch.ElapsedMilliseconds}");
        }

    }
}
